//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.ruoyi.live.platform.service;

import com.ruoyi.live.base.domain.SystemParam;
import com.ruoyi.live.base.mapper.SystemParamMapper;
import com.ruoyi.live.register.utils.RegisterContant;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

@Service
public class SystemParamService {
    private static final Logger log = LoggerFactory.getLogger(SystemParamService.class);
    @Autowired
    SystemParamMapper dao;
    @Autowired
    JdbcTemplate jdbcTemplate;

    public SystemParamService() {
    }

    @CacheEvict(
            value = {"paramCache"},
            key = "#entity.paramCode"
    )
    public void updateSystemParam(SystemParam entity, HttpServletRequest request) throws Exception {
        try {
            this.dao.updateById(entity);
            if ("USE_WORLD_RULE".equals(entity.getParamCode()) && RegisterContant.standardType()) {
                String sqlFilePath = request.getSession().getServletContext().getRealPath("/static/");
                ScriptRunner runner = new ScriptRunner(this.jdbcTemplate.getDataSource().getConnection());
                String scoreSqlFile = "init_standard_world.sql";
                if ("2".equals(entity.getParamValue())) {
                    scoreSqlFile = "init_standard.sql";
                }

                runner.setLogWriter((PrintWriter)null);
                runner.runScript(new InputStreamReader(new FileInputStream(sqlFilePath + scoreSqlFile), "UTF-8"));
                runner.closeConnection();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            log.error("更新SystemParam失败,编号SystemParamService-updateSystemParam-1,id:{}", entity.getId());
            throw new Exception("更新失败,编号SystemParamService-updateSystemParam-1");
        }
    }
}
